"ui";

var rs = null, flag = '', imei = getDeviceIdentity();
const reg_url = 'http://14.18.41.247:8060/valid/admin/api/reg', login_url = 'http://14.18.41.247:8060/valid/admin/api/login',
   activity_url = 'http://14.18.41.247:8060/valid/admin/api/act', changeStatus = 'http://14.18.41.247:8060/valid/admin/api/disc',
   app_urls = 'http://14.18.41.247:8060/valid/admin/api/updateApp';

var storage = storages.create("login");
var userName = storage.get('userName'), password = storage.get('password');
threads.start(function () {
   try {
     
      if (userName != null || storage != undefined || password != '') {
         login(userName, password);
      } else {

         showLoginUI();

         ui.run(() => {
            ui.statusBarColor("#000000")
            ui.name.setText(userName);
            ui.password.setText(password)
         })
      }
   } catch (error) {

      ui.run(() => {
         showLoginUI();
         ui.statusBarColor("#000000")
      })
   }
})


//显示登录界面
function showLoginUI() {
   ui.layout(
      <frame h={device.width / 1.5} bg='#80ffffff'>
         <img src='http://www.keaihuaidan.com/1.webp' w='*' h={device.width - 720} />
         <vertical h="auto" align="center" margin="0 50">
            <linear>
               <text w="56" gravity="center" color="#FF4FB3FF" size="16">用户名</text>
               <input id="name" w="*" h="40" />
            </linear>
            <linear>
               <text w="56" gravity="center" color="#FF4FB3FF" size="16">密码</text>
               <input id="password" w="*" h="40" password="true" />
            </linear>
            <linear gravity="center">
               <button id="login" style="Widget.AppCompat.Button.Colored" text="登录" />
               <button id="register" style="Widget.AppCompat.Button.Colored" text="注册" />
            </linear>
         </vertical>
      </frame>
   );

   ui.login.on("click", () => {
      threads.start(function () {
         let userName = ui.name.text(), password = ui.password.text();
         login(userName, password);
      })
   });
   ui.register.on("click", () => showRegisterUI());
}

//显示注册界面
function showRegisterUI() {
   ui.layout(
      <frame h={device.width / 1.5} bg='#80ffffff'>
         <img src='http://www.keaihuaidan.com/1.jpg' w='*' h={device.height / 3} />
         <vertical h="auto" align="center" margin="0 50">
            <linear>
               <text w="56" gravity="center" color="#FF4FB3FF" size="16">用户名</text>
               <input id='uname' w="*" h="40" />
            </linear>
            <linear>
               <text w="56" gravity="center" color="#FF4FB3FF" size="16">密码</text>
               <input id='pwd' w="*" h="40" password="true" />
            </linear>
            <linear gravity="center">
               <button id='reg' style="Widget.AppCompat.Button.Colored" >确定</button>
               <button id="cancel" style="Widget.AppCompat.Button.Colored" >取消</button>
            </linear>
         </vertical>
      </frame>
   );
   ui.cancel.on("click", () => showLoginUI());
   ui.reg.on('click', () => {
      threads.start(function () {
         let uname = ui.uname.text(), pwd = ui.pwd.text();
         if (uname == '' || uname == undefined) {
            toastLog('用户名不能为空!')
            return;
         }
         if (pwd == '' || pwd == undefined) {
            toastLog('密码不能为空!')
            return;
         }
         log(imei)
         let r = http.post(reg_url, {
            'userName': uname,
            'password': pwd,
            'imei': imei
         });

         rs = r.body.json();
         if (r.statusCode == 200) {
            if (rs.code == 0) {
               storage.put('userName', uname)
               storage.put('password', pwd)
               toastLog(rs.msg);
               ui.run(() => {
                  showLoginUI()
               })
            } else {
               toastLog(rs.msg)
            }
         } else {
            toastLog(rs.msg)
         }
      })
   })
}


function login(userName, password) {
   let r = http.post(login_url, {
      'userName': userName,
      'password': password,
      'imei': imei
   })

   if (r.statusCode == 200) {
      rs = r.body.json();
      if (rs.code == 0) {
         toastLog('登陆成功')
         ui.run(() => {
            main()
         })
      } else {
         toastLog('登陆失败')
         ui.run(() => {
            showLoginUI();
            ui.statusBarColor("#000000");
            ui.name.setText(userName);
            ui.password.setText('')
            ui.statusBarColor("#000000")
         })
      }
   } else {
      toastLog('请求失败!');
   }
}


function main() {
   var color = "#009688";
   ui.layout(
      <drawer id="drawer" >
         <vertical>
            <appbar>
               <toolbar id="toolbar" title="客户管理界面" />
               <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
               <frame>
                  <vertical h="auto">
                     <input id="name" textSize="16sp" hint="请输入客户IMEI码" textColorHint='red' />
                     <horizontal>
                        <text textSize="16sp" typeface='monospace ' textStyle='bold' textColor='#FF4FB3FF'>卡类型:</text>
                        <spinner id="sp1" entries="请选择|测试卡|周卡|月卡|终身" w='auto' textStyle='bold' textColor='#FF4FB3FF' />
                        <text textSize="16sp" w='auto' textStyle='bold' textColor='red'>激活后请提醒客户重启程序</text>
                     </horizontal>
                     <button id="submit" style="Widget.AppCompat.Button.Colored" text="确定" />
                     <linear gravity="center">
                        <button id="lock" style="Widget.AppCompat.Button.Colored" text="禁用账号" />
                        <button id="unlock" style="Widget.AppCompat.Button.Colored" text="解封账号" />
                     </linear>
                     <text textSize="16sp" typeface='monospace ' textStyle='bold' textColor='red'>请在输入客户IMEI码后选择相应的卡类型点击确定即可激活账号</text>
                     <text textSize="16sp" typeface='monospace ' textStyle='bold' textColor='red'>禁用账号默认为取消状态，如需要禁用账号，请输入禁用的IMEI码点击确定即可</text>
                  </vertical>
               </frame>
               <frame>
                  <vertical h="auto">
                     <input id="app_url" textSize="16sp" hint="请输入更新链接" textColorHint='red' />
                     <input id='app_version' hint="请输入版本号" textColorHint='red' />
                     <button id="onsubmit" style="Widget.AppCompat.Button.Colored" text="提交" />
                  </vertical>
               </frame>
               <frame>
                  <vertical>
                     <list id="todoList">
                        <card w="*" h="70" margin="10 5" cardCornerRadius="2dp"
                           cardElevation="1dp" foreground="?selectableItemBackground">
                           <horizontal gravity="center_vertical">
                              <View bg={getColor()} h="*" w="10" />
                              <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                 <text id="title" text="{{this.imei}}" textColor="#222222" textSize="14sp" maxLines="1" />
                                 <text id="title" text="到期时间:{{this.dateTime}}" textColor="#222222" textSize="14sp" maxLines="1" />
                                 <text text="状态:{{this.status==0?'正常':'禁用'}}" textColor="#999999" textSize="14sp" maxLines="1" />
                              </vertical>
                           </horizontal>
                        </card>
                     </list>
                  </vertical>
               </frame>
            </viewpager>
         </vertical>
         <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg" />
            <list id="menu">
               <horizontal bg="?selectableItemBackground" w="*">
                  <img w="50" h="50" padding="16" src="{{this.icon}}" tint={color} />
                  <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center" />
               </horizontal>
            </list>
         </vertical>
      </drawer>
   );

   //创建选项菜单(右上角)
   ui.emitter.on("create_options_menu", menu => {
      menu.add("关于");
      menu.add("退出");
   });

   //监听选项菜单点击
   ui.emitter.on("options_item_selected", (e, item) => {
      switch (item.getTitle()) {
         case "关于":
            alert("关于", "客户管理由Mr.Zul利用Autojs模板二次开发而成，如有业务需求请联系作者QQ:994434661");
            break;
         case "退出":
            ui.run(() => {
               ui.finish();
            })
            exit;
            break;
      }
      e.consumed = true;
   });
   activity.setSupportActionBar(ui.toolbar);

   //设置滑动页面的标题
   ui.viewpager.setTitles(["账号状态", "app更新",'用户列表']);
   //让滑动页面和标签栏联动
   ui.tabs.setupWithViewPager(ui.viewpager);
   onloads()
   ui.submit.on('click', () => {
      threads.start(function () {
         let cardType = ui.sp1.getSelectedItemPosition(), imeiNum = ui.name.text();
         if (imeiNum == '' || imeiNum == null || imeiNum == undefined) {
            toastLog('请输入IMEI码');
            return;
         }

         if (cardType == 0) {
            toastLog('请选择卡类型');
            return;
         }
         let r = http.post(activity_url, {
            'imei': imeiNum,
            'type': cardType,
            'flag': imei
         })

         if (r.statusCode == 200) {
            rs = r.body.json();
            if (rs.code == 0) {
               toastLog('账号激活成功，请客户重启软件!')
            } else {
               toastLog(rs.msg)
            }
         } else {
            toastLog('请求失败,状态码:' + r.statusCode)
         }
      })
   })

   ui.lock.on('click', () => {
      threads.start(function () {
         let imeiNum = ui.name.text();
         if (imeiNum == '' || imeiNum == null || imeiNum == undefined) {
            toastLog('请输入IMEI码');
            return;
         }
         let r = http.post(changeStatus, {
            'imei': imeiNum,
            'status': 1
         })

         if (r.statusCode == 200) {
            rs = r.body.json();
            if (rs.code == 0) {
               toastLog(rs.msg)
            } else {
               toastLog(rs.msg)
            }
         } else {
            toastLog(rs.msg)
         }
      })
   })

   ui.unlock.on('click', () => {
      threads.start(function () {
         let imeiNum = ui.name.text();
         if (imeiNum == '' || imeiNum == null || imeiNum == undefined) {
            toastLog('请输入IMEI码');
            return;
         }
         let r = http.post(changeStatus, {
            'imei': imeiNum,
            'status': 0
         })

         if (r.statusCode == 200) {
            rs = r.body.json();
            if (rs.code == 0) {
               toastLog("解封账号成功")
            } else {
               toastLog(rs.msg)
            }
         } else {
            toastLog(rs.msg)
         }
      })
   })

   ui.onsubmit.on('click', () => {
      threads.start(function () {
         let url = ui.app_url.text(), version = ui.app_version.text();
         if (url == "" || url == null || url == undefined) {
            toastLog('链接地址不能为空!');
            return;
         }
         if (version == "" || version == null || version == undefined) {
            toastLog('版本号不能为空!');
            return;
         }
         let r = http.post(app_urls, {
            'url': url,
            'version': version,
            'flag':imei
         })
         if (r.statusCode == 200) {
            rs = r.body.json();
            if (rs.code == 0) {

               ui.run(() => {
                  ui.app_url.setText('')
                  ui.app_version.setText('')
               })

               toastLog(rs.msg)
            } else {
               toastLog(rs.msg)
            }
         } else {
            toastLog(rs.msg)
         }
      })

   })
}

function getColor() {
      var materialColors = ["#e91e63", "#ab47bc", "#5c6bc0", "#7e57c2", "##2196f3", "#00bcd4",
         "#26a69a", "#4caf50", "#8bc34a", "#ffeb3b", "#ffa726", "#78909c", "#8d6e63"];
      return materialColors[random(0, materialColors.length)]
}

function onloads() {
   threads.start(function () {
      let url = 'http://14.18.41.247:8060/valid/admin/api/queryInfo', rs = '', todoList = [];

      let r = http.get(url, {'imei':imei});
      if (r.statusCode == 200) {
         rs = r.body.json();
         if (rs.code == 0) {
            for (let i = 0; i < rs.data.length; i++) {
               todoList.push(rs.data[i])
            }
         }
      }

      ui.run(() => {
         ui.todoList.setDataSource(todoList);
      })

   })
}

function getDeviceIdentity() {
   let id = null;
   if (device.sdkInt >= 29) {
      let mac = device.getMacAddress()
      if (mac == null || mac == "" || mac == "00:00:00:00:00:00") return null
      return "M-" + xx(mac.replace(/:/, ""))
   }
   try {
      id = android.os.Build.getSerial();
   } catch (e) {
      if (e.javaException instanceof java.lang.SecurityException)
         return null;
   }
   if (id && id.toLowerCase() != "unknown") {
      id = xx(id)
   } else if (device.serial && device.serial.toLowerCase() != "unknown") {
      id = xx(device.serial)
   } else {
      let iii = null;
      let tm = context.getSystemService("phone");
      if (!tm) return null;
      try {
         iii = tm.getImei(0);
      } catch (e) {
         if (e.javaException instanceof java.lang.SecurityException)
            return null;
      }
      if (iii == null || iii == "000000000000000") {
         iii = device.getIMEI();
      }
      if (iii != null) id = "I-" + xx(iii);
      else return null
   }
   return id;
}

function xx(str) {
   var mod = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"
   var arr = str.split("");
   for (var i in arr) arr[i] = mod[(mod.indexOf(arr[i]) + 10) % mod.length]
   return arr.reverse().join("")
}




